掌握 進階控制流程 意味著超越線性執行,運用複雜的迭代模式與多路分支。透過整合 do-while 迴圈、 switch 語句以及 break/continue 關鍵字,程式設計師能精確地決定機器如何處理複雜邏輯。
1. for 迴圈的結構解析
這個 for 迴圈是一種結構化的迭代模式,包含三個明確的階段: 初始化 (定義起始點), 檢查 (條件表達式),以及 更新 (修改狀態)。例如, for (var i = 0; i <= 12; i += 2) 展現了每次遞增兩步的精確控制。
2. 中斷執行
精準度來自於邏輯性的中斷: break 語句會立即跳出封閉的迴圈,而 continue 則跳過當前程式碼區塊的執行,直接進入下一輪迭代。取餘運算子(%)在這裡至關重要,用來判斷可整除性(例如, current % 7 == 0)。
do {
var yourName = prompt("你是誰?");
} while (!yourName);
var yourName = prompt("你是誰?");
} while (!yourName);
3. 多向分支
這個 switch 語句提供了比長串 if-else 鏈條更乾淨的替代方案,當需要針對單一表達式檢查多個離散值時。
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
What is unique about a
do loop compared to a while loop?It never executes if the condition is false.
It always executes its body at least once.
It is faster for mathematical calculations.
It automatically increments the counter.
✅ Correct!
Correct! A do-while loop executes the body first and only tests the stop condition afterward.❌ Incorrect
Incorrect. The do loop structure ensures the first run happens before the check.QUESTION 2
Which keyword immediately exits the current loop entirely?
continue
exit
break
return
✅ Correct!
The break statement jumps control immediately out of the enclosing loop.❌ Incorrect
The continue keyword only skips the current iteration, not the whole loop.QUESTION 3
Write a loop that makes seven calls to console.log to output a triangle of # characters. [Word Count Required: 50 words]
for(let line = '#'; line.length < 8; line += '#') console.log(line);
while(i < 7) { console.log('#'); }
✅ Correct!
Model Answer: To solve this, initialize a string variable with a single '#' character. In each iteration of a 'for' loop, check if the string's length is less than eight. Inside the body, log the string, then update it by appending another '#' until seven lines are printed successfully.❌ Incorrect
You must use the length of the string or a counter to increment the characters on each line.QUESTION 4
Write the 'FizzBuzz' program logic for numbers 1 to 100. [Word Count Required: 100 words]
Implementation using % 3, % 5, and % 15.
✅ Correct!
Model Answer: This program uses a 'for' loop to iterate from 1 to 100. Inside, we apply conditional branching. First, check if a number is divisible by both 3 and 5 using the remainder operator (n % 15 == 0) to print 'FizzBuzz'. If that fails, check if it is divisible by 3 for 'Fizz' or 5 for 'Buzz'. If none match, print the number itself. This logic demonstrates how order of operations in conditional branches is critical; checking for the combined 'FizzBuzz' case first prevents the program from incorrectly stopping at the simpler 'Fizz' or 'Buzz' conditions.❌ Incorrect
Ensure you check for the common multiple (15) first, otherwise 15 will only print 'Fizz'.QUESTION 5
Explain the logic to create an 8x8 checkerboard grid string. [Word Count Required: 150 words]
Nested loops with newline characters and a size variable.
✅ Correct!
Model Answer: To build an 8x8 checkerboard, we represent the grid using a single string and two nested 'for' loops. The outer loop handles the vertical rows (y-axis), while the inner loop handles the horizontal columns (x-axis). At each grid position (x, y), we decide whether to add a space or a '#' character. The mathematical trick is to check if the sum of the current x and y indices is even or odd: (x + y) % 2 == 0. If even, add a space; if odd, add '#'. After the inner loop completes a row, append a newline character ('\n') to start the next line. By defining a 'size' variable (e.g., size = 8) and using it as the loop limit for both x and y, the program becomes dynamic. This allows the user to generate a grid of any dimensions (e.g., 10x10 or 20x20) simply by changing one variable value.❌ Incorrect
Remember to use a nested loop structure and the modulo operator on the sum of indices to create the alternating pattern.Case Study: Modular Pattern Generation
Applying Control Flow to Structural Data
You are tasked with building a terminal-based UI component that generates a grid for a game. You must use modular arithmetic to determine tile patterns and a 'switch' statement to handle different terrain types ('grass', 'water', 'mountain').
Q
How would you modify a grid loop to only place a 'mountain' symbol every 7 tiles?
Solution:
Inside the loop, use the condition 'if (index % 7 == 0)'. This leverages the remainder operator to identify every seventh iteration regardless of the total grid size.
Inside the loop, use the condition 'if (index % 7 == 0)'. This leverages the remainder operator to identify every seventh iteration regardless of the total grid size.
Q
Why is a 'switch' better than 'if-else' for handling 5 different terrain types?
Solution:
A 'switch' statement is more readable for discrete values. It provides a structured 'default' case for error handling and avoids the visual clutter of repetitive 'else if' blocks, making the code easier for humans to scan.
A 'switch' statement is more readable for discrete values. It provides a structured 'default' case for error handling and avoids the visual clutter of repetitive 'else if' blocks, making the code easier for humans to scan.